<?php
/** .-------------------------------------------------------------------
* |  Software: [HDPHP framework]
* |      Site: www.hdphp.com
* |-------------------------------------------------------------------
* |    Author: 向军 <2300071698@qq.com>
* |    WeChat: aihoudun
* | Copyright (c) 2012-2019, www.houdunwang.com. All Rights Reserved.
* '-------------------------------------------------------------------*/

namespace system\model;

use hdphp\Model\Model;

class User extends Model{
	//数据表
	protected $table = "user";

	//允许填充字段
	protected $allowFill = [ ];

	//禁止填充字段
	protected $denyFill = [ ];

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
		[ 'username', 'required', '用户名不能为空', self::MUST_VALIDATE,self::MODEL_BOTH ],
		[ 'password', 'required', '请输入密码',  self::MUST_VALIDATE,self::MODEL_BOTH ],
		[ 'code', 'captcha', '验证码输入错误',  self::MUST_VALIDATE,self::MODEL_BOTH ],
	];

	//自动完成
	protected $auto=[
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];

	//自动过滤
    protected $filter=[
        //[表单字段名,过滤条件,处理时间]
    ];

	//时间操作,需要表中存在created_at,updated_at字段
	protected $timestamps=false;

	public function reg(){
		$user=new User();
		$data=Db::table('user')->where('username',Q('post.username'))->first();

		if($data['username']==Q('post.username')){
			$this->error = "用户名已存在";
			return false;
		}
		if(Q('post.password')!=Q('post.confirm_password')){
			$this->error="密码不一致";
			return false;

		}
		$user['username']=Q('post.username');
		$user['password']=Crypt::encrypt(Q('post.password'));
		return $user->save();
	}
	/*登录*/
	public function login(){
		Validate::make([
			[ 'username', 'required', '用户名不能为空', 3 ],
			[ 'password', 'required', '请输入密码', 3 ],
		]);
		$data = Db::table('user')->where('username',$_POST['username'])->first();
		//判断用户名是否正确
		if($_POST['username'] != $data['username']){
			$this->error = "用户名错误";return false;
		}
		//判断密码是否正确
		if(Crypt::encrypt($_POST['password']) != $data['password']){
			$this->error = "密码错误";return false;
		}
		//走到这说明用户名密码都正确
		$_SESSION['home']['uid'] = $data['uid'];
		$_SESSION['home']['username'] = $data['username'];
		return true;
	}
}